import http from 'http';
import https from 'https';
import httpProxy from 'http-proxy'
import portfinder from 'portfinder';
import {logger} from "@/main/log.js";
import {getCredentials} from "@/main/lcu/LcuCertificate.js";
import store, {store_field_lcu_certificate} from "@/main/store/store.js";


async function createHttpProxy(isReConnect,originPort) {

    let port ;
    logger.debug(`获取到可用的代理端口服务${port}`)
    if(isReConnect){
        port=originPort;
    }else{
        port  = await portfinder.getPortPromise({
            port: 50000
        });
    }

    process.env.LCU_PORT_PROXY = port;
    // 1. 创建代理服务器（配置忽略SSL证书）
    const proxy = httpProxy.createProxyServer({
        changeOrigin: true,                      // 修改主机头为目标URL
        secure: false,                           // 关键：忽略SSL证书验证
        agent: new https.Agent({                 // 创建自定义Agent
            rejectUnauthorized: false              // 忽略证书错误
        }),
        protocolRewrite: 'https',               // 强制使用HTTPS协议
        headers: {
            'Authorization': getCredentials().token
        }
    }).on('error', (err, req, res) => {
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end(`代理错误: ${err.message}`);
    });

    const server = http.createServer((req, res) => {
        // 可选：添加请求处理逻辑（如日志/过滤）
        // 开始代理请求
        proxy.web(req, res, {target: `https://127.0.0.1:${process.env.LCU_PORT}`});
    });

    server.listen(port, () => {
        logger.info(`代理服务器运行中 http://localhost:${port}`);
    });
    store.set(`${store_field_lcu_certificate}.proxyPort`, port);

    return {
        "server": server,
        "proxyPort": port,
    }

}

export {
    createHttpProxy
}

